package com.zero.manage.web.config;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.provider.DynamicDataSourceProvider;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.orm.jpa.vendor.Database;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

/**
 * 在同样的DataSource中，首先使用被Primary标注的DataSource
 *
 * @author zero
 */
@Configuration
@Log4j2
@Primary
public class DataSourceConfig {
    private static final String MYSQL_CREATE_DATABASE = "create database if not exists `%s` default character set utf8mb4";
    private static final String SQL_SERVER_CREATE_DATABASE = "if not exists(select 1 from sysdatabases where name = '%s') create database [%s]";

    @Value("${spring.datasource.dynamic.datasource.master.url}")
    private String datasourceUrl;

//    @Value("${spring.datasource.druid.driver-class-name}")
//    private String driverClassName;

    @Value("${spring.datasource.dynamic.datasource.master.username}")
    private String username;

    @Value("${spring.datasource.dynamic.datasource.master.password}")
    private String password;

    @Value("${spring.jpa.database}")
    private Database database;
    @Autowired
    private DynamicDataSourceProperties properties;

    @Bean
    public DataSource dataSource(DynamicDataSourceProvider dynamicDataSourceProvider) {
        DynamicRoutingDataSource dataSource = new DynamicRoutingDataSource();
        dataSource.setPrimary(properties.getPrimary());
        dataSource.setStrict(properties.getStrict());
        dataSource.setStrategy(properties.getStrategy());
        dataSource.setProvider(dynamicDataSourceProvider);
        dataSource.setP6spy(properties.getP6spy());
        dataSource.setSeata(properties.getSeata());
        switch (database) {
            case SQL_SERVER:
                sqlServerDatabase();
                break;
            default:
                mysqlDatabase();
        }
        return dataSource;
    }

    private void mysqlDatabase() {
        //获取数据库名
        String url01 = datasourceUrl.substring(0, datasourceUrl.indexOf("?"));
        String url02 = url01.substring(0, url01.lastIndexOf("/")) + datasourceUrl.substring(datasourceUrl.indexOf("?"));
        String databaseName = url01.substring(url01.lastIndexOf("/") + 1);
        try (
                // 连接已经存在的数据库，如：mysql
                Connection connection = DriverManager.getConnection(url02, username, password);
                Statement statement = connection.createStatement()) {
//            Class.forName(driverClassName);
            // 创建数据库
            statement.executeUpdate(String.format(MYSQL_CREATE_DATABASE, databaseName));
        } catch (Exception e) {
            log.error("创建MYSQL数据库失败", e);
        }
    }

    private void sqlServerDatabase() {
        String databaseName = datasourceUrl.substring(datasourceUrl.indexOf(";databaseName=") + 14);
        String url02 = datasourceUrl.substring(0, datasourceUrl.indexOf(";databaseName=" + databaseName));
        try (
                // 连接已经存在的数据库，如：mysql
                Connection connection = DriverManager.getConnection(url02, username, password);
                Statement statement = connection.createStatement()) {
//            Class.forName(driverClassName);
            // 创建数据库
            statement.executeUpdate(String.format(SQL_SERVER_CREATE_DATABASE, databaseName, databaseName));
        } catch (Exception e) {
            log.error("创建SQL_SERVER数据库失败", e);
        }
    }
}
